package com.proxy.daijia.map.service.impl;




import com.alibaba.fastjson.JSONObject;
import com.proxy.daijia.common.execption.ProxyException;
import com.proxy.daijia.common.result.ResultCodeEnum;
import com.proxy.daijia.map.service.MapService;
import com.proxy.daijia.model.form.map.CalculateDrivingLineForm;
import com.proxy.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;

    //计算驾驶线路
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {

        //定义请求接口
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        //封装请求参数
        Map<String, String> params = new HashMap<>();
        params.put("from", calculateDrivingLineForm.getStartPointLatitude() + "," + calculateDrivingLineForm.getStartPointLongitude());
        params.put("to", calculateDrivingLineForm.getEndPointLatitude() + "," + calculateDrivingLineForm.getEndPointLongitude());
        params.put("key",key);

        //发送请求
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, params);

        int status = result.getIntValue("status");
        if (status != 0){
            new ProxyException(ResultCodeEnum.MAP_FAIL);
        }

        //获取结果
        //JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        //封装返回结果
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //方案估算时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //方案总距离
        drivingLineVo.setDistance(route.getBigDecimal("distance").divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_UP));
        //方案路线坐标点串
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        return drivingLineVo;
    }
}
